js.underas.net.SimpleToolBar = new Class({
	"Extends":js.underas.core.Component
	,"_varmod":null
	,"initialize":function(){
		this.parent('div','<div class="btn-group btn-group-justified"></div>');
		this.getEle().addClass("ToolBar col-sm-offset-0 col-sm-12 col-xs-12");
		this.getEle().setStyles({"margin-bottom":"10px","z-index":"13"});
	}
	,"addButton":function(nbuttom){
		nbuttom.getEle(".btnLabel").addClass("hidden-xs");
	    this.getEle("div.btn-group").grab(nbuttom.getEle());	
	}
	,"setVarModule":function(p_varmod){
		this.getEle(".btn-group").set("data-varmod",p_varmod);
		this._varmod=p_varmod;
	}
	,"getVarModule":function(){
		return this._varmod;
	}
	,"getModule":function(){
		if(!this.getVarModule()){
			this._varmod = this.findVarModule();
		}		
		return window[this.getVarModule()];
	}
	,"findVarModule":function(){
		if(!this._varmod){			
			this.setVarModule(this._varmod);
		}
		return this._varmod;
	}
});

js.underas.net.ToolBar = new Class({
	"Extends":js.underas.net.SimpleToolBar
	,"_config":{}
	,"_istoolbar":true
	,"_isactive":false
	,"initialize":function(p_config){
		this.parent();
		this._istoolbar = true;
		this._isactive = false;
		this._config = Object.merge({"domain":""},p_config);
		this.btAdd = new js.underas.controller.Button("Novo");
		this.btAdd.setIcon("plus");
		this.btAdd.addEvent('click',function(event){					
			event.preventDefault();
			var tfield = this.getModule().getIdField();
			this.getModule()[tfield].setValue("");
			this.getModule().clearFormItem();
		}.bind(this));
		
		this.btDel = new js.underas.controller.Button("Excluir");
		this.btDel.setIcon("minus-sign");
		this.btDel.addEvent('click',this.deleteItem.bind(this));
		
		this.btSave = new js.underas.controller.Button("Salvar");
		this.btSave.setIcon("floppy-disk");
		this.btSave.addEvent('click',this.saveItem.bind(this));
		
		//this.btReload = new js.underas.controller.Button("Carregar");
		//this.btReload.setIcon("refresh");
		//this.btReload.addEvent('click',this.reloadItens.bind(this));
		
		this.addButton(this.btAdd);
		this.addButton(this.btDel);
		this.addButton(this.btSave);
		//this.addButton(this.btReload);		
	}
	,"getDefaultRequest":function(p_act,p_method){
		return {"format":js.underas.net.RequestManager.format,"url":js.underas.net.RequestManager.url+this._config.domain+p_act,"method":p_method,"puid":this.findVarModule()};
	}
	,"updateItem":function(p_objToUpdate){		
		var req_objToUpdate = Object.merge(this.getDefaultRequest("/","put"),{"data":p_objToUpdate});		
		req_objToUpdate = this.getModule().beforeUpdate(req_objToUpdate,this.getModule().getMainList().getSelectedItem());
		if(req_objToUpdate){
			var tmpObjectMerged = Object.merge(this.getModule().getMainList().getSelectedItem(),req_objToUpdate.data);
			this.getModule().getMainList().updateItem(tmpObjectMerged);
			js.underas.net.RequestManager.addRequest(req_objToUpdate);
			tmpObjectMerged = null;
		}
	}
	,"insertItem":function(p_objToInsert){
		var req_objToInsert = Object.merge(this.getDefaultRequest("/","post"),{"data":p_objToInsert});
		var modTmp = this.getModule();
		var tfield1 = modTmp.getIdField();
		var tcolumn1 = modTmp[tfield1].getColumn();
		delete req_objToInsert["data"][tcolumn1];
		req_objToInsert = this.getModule().beforeInsert(req_objToInsert);
		if(req_objToInsert){			
			js.underas.net.RequestManager.addRequest(Object.merge(req_objToInsert,{
				"onLoad":function(dta_new){
					if(!dta_new.erro){
						var tfield2 = this.getModule().getIdField();
						var tcolumn2 = this.getModule()[tfield2].getColumn();
						req_objToInsert["data"][tcolumn2] = dta_new;						
						delete req_objToInsert["format"];
						delete req_objToInsert["onLoad"];
						delete req_objToInsert["puid"];
						delete req_objToInsert["method"];
						delete req_objToInsert["url"];	
						this.getModule().getMainList().insertItem(req_objToInsert.data,'bottom');					
						//insert embed doc
						if(this.getModule()._embedFather){
							var tmpEmbedFather = this.getModule()._embedFather;
							var tmpEmbedItem = this.getModule()._embedItem;
							var tmC = 0;
							if(!window[tmpEmbedFather].getMainList().getSelectedItem()[tmpEmbedItem]){
								window[tmpEmbedFather].getMainList().getSelectedItem()[tmpEmbedItem] = []; 
							}else{
								//tmC = window[tmpEmbedFather].getMainList().getSelectedItem()[tmpEmbedItem].length;
							};
							//window[tmpEmbedFather].getMainList().getSelectedItem()[tmpEmbedItem][tmC] = req_objToInsert.data;
						}
						//fim insert embed doc
					};
				}.bind(this)
			}));
		}
	}
	,"deleteItem":function(event){
		if(event){
			event.preventDefault();
		};
		//var p_objToDelete = {};
		var modTmp =this.getModule();
		//var tmpColumns = modTmp.getColumns();
		/*
		tmpColumns.each(function(cfield,index){
			//var tmpField = this.getModule()[cfield["field"]];			
			var fieldTmp = cfield["field"];
			if(!modTmp[fieldTmp]){
				console.log("delete item erro# field "+fieldTmp+" not exist!");
			}else{
				p_objToDelete[cfield["column"]] = modTmp[fieldTmp].getValue();
			}			
		});	
		*/
		//var tfield = modTmp.getIdField();
		
		var tfield = modTmp.getIdField();
		//modTmp[tfield].getValue();
		var tcolumn = modTmp[tfield].getColumn();
		
		var p_req_delete = this.getDefaultRequest("/"+modTmp[tfield].getValue(),"delete");
		//p_objToDelete[tcolumn] = modTmp[tfield].getValue();		
		//p_objToDelete = Object.merge(this.getDefaultRequest("/"+p_objToDelete[tcolumn],"delete"),p_objToDelete);
		p_req_delete["onLoad"]=function(dta){			
			if(this.getModule().getMainList()){				
				var tmpEmbedFather = this.getModule()._embedFather;
				if(tmpEmbedFather){					
					var tmpEmbedItem = this.getModule()._embedItem;
					var tmC = 0;
					if(window[tmpEmbedFather].getMainList().getSelectedItem()[tmpEmbedItem]){
						var indexEmbed = this.getModule().getMainList().getSelectedIndex();
						//var indexEmbed = window[tmpEmbedFather].getMainList().getSelectedItem()[tmpEmbedItem].getDataProvider().indexOf(this.getMainList().getSelectedItem().idPerfil);
						if (indexEmbed > -1) {
							window[tmpEmbedFather].getMainList().getSelectedItem()[tmpEmbedItem].splice(indexEmbed, 1);
							//this.aviso.setText("Salve o cadastro de usuario para completar a acao!");
							//this.aviso.setType(js.underas.controller.AlertMsg.TP_INFO);
						};
						//window[tmpEmbedFather].getMainList().getSelectedItem()[tmpEmbedItem] = []; 
					};
					//window[tmpEmbedFather].getMainList().getSelectedItem()[tmpEmbedItem][tmC] = req_objToInsert.data;
				};
				this.getModule().getMainList().removeItem(this.getModule().getMainList().getSelectedItem());
			};
			this.getModule().clearFormItem();
			this.getModule().getMainList().changeToIndex(0);
			//ir para o primeiro item apos limpar forms			
		}.bind(this);
		
		p_req_delete = this.getModule().beforeDelete(p_req_delete,this.getModule().getMainList().getSelectedItem());
		if(p_req_delete){
			//this.getModule().getMainList().removeItem(p_objToDelete);
			js.underas.net.RequestManager.addRequest(p_req_delete);
		};
	}
	,"activate":function(p_on){		
		if(this._isactive!=p_on){
			this._isactive=p_on;
			var modTmp = this.getModule();
			var tmpList = modTmp.getMainList();
			if(p_on && tmpList){
				if(!tmpList.itemChange){
					if(tmpList["pageRequest"]){
						tmpList["pageRequest"] = function(p_obj){
							var p_req_reload = Object.merge(this.getDefaultRequest("/","get"),p_obj);						
							p_req_reload = this.getModule().beforeQuery(p_req_reload);		
							if(p_req_reload){									
								if(!p_req_reload["onLoad"]){
									p_req_reload["onLoad"] = function(dta_ret){
										var mainlisttmp = this.getModule().getMainList();
										mainlisttmp.setDataProvider(dta_ret);
										if(mainlisttmp["_pag"]){
											//mainlisttmp["_pag"]++;
											mainlisttmp["_loading"] = false;
											//this.getModule().getMainList()["_pag"]++;
											mainlisttmp.getEle(".tilecellgrid").scrollTo(0,10);						
											//this._loading=true;
										}
									}.bind(this);
								}										
								js.underas.net.RequestManager.addRequest(p_req_reload);
							}
						}.bind(this);
					}
					tmpList["itemChange"] = function(p_item){
						if(p_item){
							var tmpColumns = modTmp.getColumns();			
							tmpColumns.each(function(cfield,index){
								var fieldTmp = cfield["field"];
								var tmpValue = p_item[cfield["column"]];
								var tmpField = modTmp[fieldTmp];
								if(!tmpField){
									console.log("change item #erro: field "+fieldTmp+" not exist!");
								}else if(tmpField.isBlankWhenNull()&&(tmpValue=="undefined"||tmpValue=="null"||(!tmpValue))){
									tmpField.setValue("");
								}else{
									tmpField.setValue(tmpValue);
								};
							});
						};
						modTmp.getAssociations().each(function(value,index){
							if(value["embed"]){
								if(value["act"]!=""){
									//var selectedInd = modTmp.getMainList().getSelectedIndex();								
									//modTmp.getMainList().getDataProvider().get(selectedInd)[value["embed"]];
									//value["p"] = modTmp.getMainList().getSelectedItem()[value["embed"]];
									value["p"] = [modTmp.getMainList().getSelectedItem()[value["embed"]]];
									//console.log(value["embed"]);
									//console.log(modTmp.getMainList().getDataProvider().get(selectedInd)[value["embed"]]);
									//menu.getMainList().setDataProvider(
									//perfil.getMainList().getSelectedItem().menus
									//);
								};
							}else if(p_item){
								if(p_item[value["field"]]!=""){
									var idFieldMainTmp  = modTmp[value["field"]].getValue();
									//value["p"] = [p_item[value["field"]]];
									value["p"] = [idFieldMainTmp];
								};
							};
							js.underas.core.Underas.loadModule(value);											
						});
					}.bind(this);	
				};	
			}else if(this.getModule().getMainList()){
				this.getModule().getMainList().itemChange = null;
			};
		};	
	}	
	,"reloadItens":function(event){
		if(event){
			event.preventDefault();
		};
		var p_obj = {};
		if(this.getModule().getMainList()["_pag"]){
			p_obj=this.getModule().getMainList().getPaginationParam();
		};		
		var p_req_reload = Object.merge(this.getDefaultRequest("/","get"),p_obj);
		p_req_reload =  this.getModule().beforeQuery(p_req_reload);		
		if(p_req_reload){		
			if(!p_req_reload["onLoad"]){
				p_req_reload["onLoad"] = function(dta_ret){
					var mainlisttmp = this.getModule().getMainList();
					mainlisttmp.setDataProvider(dta_ret);
					if(mainlisttmp["_pag"]){
						//mainlisttmp["_pag"]++;
						mainlisttmp["_loading"] = false;
						//this.getModule().getMainList()["_pag"]++;
						mainlisttmp.getEle(".tilecellgrid").scrollTo(0,10);						
						//this._loading=true;
					};
					this.getModule().getMainList().changeToIndex(0);
				}.bind(this);
			}
			js.underas.net.RequestManager.addRequest(p_req_reload);
		}
		this.activate(true);			
	}
	,"syncItem":function(){
		var rs_objt = {};
		var modTmp =this.getModule();
		var tmpColumns = modTmp.getColumns();	
		var anyinvalidfield = false;
		tmpColumns.each(function(cfield,index){	
			var fieldTmp = cfield["field"];
			if(!modTmp[fieldTmp]){
				console.log("save item erro# field "+fieldTmp+" not exist!");
			}else{			
				var tmpCampo = modTmp[fieldTmp];
				rs_objt[cfield["column"]] = tmpCampo.getValue();
				if(!tmpCampo.isPrimaryKey()){
					if(tmpCampo.isValid()||tmpCampo.isTransient()){
						tmpCampo.setValid(true);
					}else{
						tmpCampo.setValid(false);
						anyinvalidfield = true;
					};
				};	
			};			
		});		
		if(anyinvalidfield){
			return null;
		};		
		return rs_objt;
	}
	,"saveItem":function(event){
		if(event){
			event.preventDefault();
		};		
		var objToSave = {};
		var modTmp =this.getModule();	
		objToSave = this.syncItem();
		if(objToSave){
			objToSave = modTmp.beforeSave(objToSave);		
			if(objToSave){
				var pkC =  modTmp.getIdField();
				if(modTmp[pkC].getValue()==""){
					this.insertItem(objToSave);
				}else{
					this.updateItem(objToSave);
				};
			};
		};
	}
});
